package ui.fragment.PosControl;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import Utils.ToastUtil;
import base.BaseBiz;
import base.LazyFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import coom.MyType;
import dao.BackFlowDevicesInput;
import event.CloseActEvent;
import event.HasPushEvent;
import event.NetErrorEvent;
import event.PosControlEvent;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import ui.activity.poscontrol.adapter.PushBackRecordOtherPeopleAdapter;
import ui.activity.poscontrol.beanmodel.MyPosBean;
import ui.activity.poscontrol.beanmodel.PosInfoBean;
import ui.activity.poscontrol.beanmodel.PushBackPeopleBean;
import ui.activity.poscontrol.beanmodel.PushBackPosBean;
import ui.activity.poscontrol.biz.MyPosControlBiz;
import ui.activity.poscontrol.component.DaggerMyPosControlComponent;
import ui.activity.poscontrol.contract.MyPosControlContract;
import ui.activity.poscontrol.module.MyPosControlModule;
import ui.activity.poscontrol.presenter.MyPosControlPresenter;

/**
 * Created by fangjunsong on 2019年3月19日17:03:30.
 * <p>
 * 回拨记录-接收的
 */

public class PushBackRecordOtherFra extends LazyFragment implements MyPosControlContract.View {


    @Inject
    MyPosControlPresenter presenter;
    @Inject
    MyPosControlBiz biz;


    @BindView(R.id.pushpeople_list)
    RecyclerView rv;
    @BindView(R.id.posrecord_txt_total)//终端数量txt
            TextView posrecord_txt_total;
    @BindView(R.id.posrecord_txt_jh)
    TextView posrecord_txt_jh;
    @BindView(R.id.allow_btn)
    TextView allow_btn;

    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.deallow_btn)
    TextView deallow_btn;
    List<PushBackPeopleBean> userInfoData = new ArrayList<>();
    PushBackRecordOtherPeopleAdapter adp;
    private List<BackFlowDevicesInput.SnInfoBean> snInfo = new ArrayList<>();
    public List<String> mSelectedDevices = new ArrayList<>();
    private boolean isPrepared;// 界面否
    private boolean isALeady = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.activity_pushbackrecordother, container, false);
        DaggerMyPosControlComponent.builder().myPosControlModule(new MyPosControlModule(this)).build().inject(this);
        ButterKnife.bind(this, view);
        presenter.setBiz(biz);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setItemAnimator(new DefaultItemAnimator());
        rv.addItemDecoration(new DividerItemDecoration(getActivity(), 1));

        isPrepared = true;

        allow_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
        deallow_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                desubmit();
            }
        });

        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData();
            }
        });
        return view;
    }

    @Override
    protected void lazyLoad() {
        if (isPrepared && isVisible && isALeady) {
            // TODO 在这里处理逻辑
            getData();
            isALeady = false;
        }
    }
    private void submit(){
        BackFlowDevicesInput input = new BackFlowDevicesInput();
        input.setCustomerId(TobuyApplication.getCustomId());
        input.getSnInfo().addAll(snInfo);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(input));
        biz.backFlowAllowDevices(requestBody, new BaseBiz.Callback<Object>() {
            @Override
            public void onSuccess(Object info) {
                ToastUtil.show(getActivity(),"确认成功");
                posrecord_txt_jh.setText("已选择：0" + "台");
                for ( int i = 0;i<userInfoData.size();i++){
                    userInfoData.get(i).getPosRecords().clear();
                    break;
                }
                getData();

            }
            @Override
            public void onFailure(Object info) {
            }
        });
    }
    private void desubmit(){
        BackFlowDevicesInput input = new BackFlowDevicesInput();
        input.setCustomerId(TobuyApplication.getCustomId());
        input.getSnInfo().addAll(snInfo);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(input));
        biz.backFlowDeAllowDevices(requestBody, new BaseBiz.Callback<Object>() {
            @Override
            public void onSuccess(Object info) {
                ToastUtil.show(getActivity(),"拒绝成功");
                posrecord_txt_jh.setText("已选择：0" + "台");
                for ( int i = 0;i<userInfoData.size();i++){
                        userInfoData.get(i).getPosRecords().clear();
                    break;
                }
                getData();

            }
            @Override
            public void onFailure(Object info) {
            }
        });
    }
    private void getData() {
        userInfoData.clear();
        snInfo.clear();
        biz.queryPushBackRecordPeopleData(TobuyApplication.getCustomId(), 2, new BaseBiz.Callback<List<PushBackPeopleBean>>() {
            @Override
            public void onSuccess(List<PushBackPeopleBean> pushBackPeopleBean) {
                ptr.onRefreshComplete();
                int totalCount =0;
                for (int i = 0;i<pushBackPeopleBean.size();i++){
                    totalCount+= pushBackPeopleBean.get(i).getCount();
                }

                posrecord_txt_total.setText("终端数量："+totalCount);
                userInfoData.addAll(pushBackPeopleBean);
//                if (null == adp) {
                    adp = new PushBackRecordOtherPeopleAdapter(getActivity(), userInfoData);
                    rv.setAdapter(adp);
//                } else {
//                    adp.setData(userInfoData);
//                }
            }

            @Override
            public void onFailure(List<PushBackPeopleBean> pushBackPeopleBean) {
                ptr.onRefreshComplete();
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(PosControlEvent event) {
        mSelectedDevices.clear();
        snInfo.clear();
        for (int i = 0;i<userInfoData.size();i++){
            for (int j = 0;j<userInfoData.get(i).getPosRecords().size();j++){
                if(userInfoData.get(i).getPosRecords().get(j).isIsselect()){
                    mSelectedDevices.add(userInfoData.get(i).getPosRecords().get(j).getSn());
                    boolean hastargetId = false;
                    int tagk = 0;
                    for (int k = 0;k<snInfo.size();k++ ){
                        if(null!=snInfo&&snInfo.size()>0&&userInfoData.get(i).getFromId() == snInfo.get(k).getTargetId()){
                            hastargetId = true;
                            tagk = k;
                        }
                    }
                    if(hastargetId){
                        snInfo.get(tagk).getSnList().add(userInfoData.get(i).getPosRecords().get(j).getSn());
                    }else{
                        BackFlowDevicesInput.SnInfoBean snInfoBean = new BackFlowDevicesInput.SnInfoBean();
                        snInfoBean.setTargetId(userInfoData.get(i).getFromId());
                        snInfoBean.getSnList().add(userInfoData.get(i).getPosRecords().get(j).getSn());
                        snInfo.add(snInfoBean);
                    }

                }
            }
        }
        posrecord_txt_jh.setText("已选择：" + mSelectedDevices.size()+"台");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerCancelOrder(HasPushEvent event) {
        biz.queryPushBackRecordPosData(TobuyApplication.getCustomId(),event.toId,event.descs,event.ascs,2,new BaseBiz.Callback<PushBackPosBean>() {
            @Override
            public void onSuccess(PushBackPosBean pushPosBean) {
                for ( int i = 0;i<userInfoData.size();i++){
                    if(userInfoData.get(i).getFromId() == event.toId) {
                        userInfoData.get(i).getPosRecords().clear();
                        userInfoData.get(i).getPosRecords().addAll(pushPosBean.getRecords());

                    }

                }
                if(null!=adp) {
                    adp.setData(userInfoData);
                }

            }

            @Override
            public void onFailure(PushBackPosBean pushPosBean) {

            }

        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        biz.onDestory();
        ButterKnife.bind(getActivity()).unbind();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseActEvent(CloseActEvent event) {
        if (event.getType() == MyType.CompleteOrder) {
        }
    }


    @Override
    public void loadMoreComplete() {

    }

    @Override
    public void hasLoadMore(boolean b) {

    }

    @Override
    public void refreshComplete() {

    }

    @Override
    public void refreshData() {

    }

    @Override
    public void upDateUI(MyPosBean infoBean, List<MyPosBean.RecordsBean> bean, boolean refresh) {

    }

    @Override
    public void upDateInfoListUI(PosInfoBean infoBean, List<PosInfoBean.RecordsBean> bean) {

    }
}